package org.sensation.server.file;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

import org.apache.log4j.Logger;
import org.sensation.file.channel.FileReadChannel;

public class SensationFileSendServer {
	private InetSocketAddress serverInetSocketAddress;
	private DatagramChannel channel;
	private FileReadChannel fileReadChannel;
	private static final Logger LOGGER = Logger.getLogger(SensationFileSendServer.class);
	
	public void start() throws IOException{
		LOGGER.debug("SensationFileSendServer start...");
		
		ByteBuffer buffer = fileReadChannel.createBuffer();
		
		while(fileReadingToBuffer(buffer)){
			sendToServer(buffer);
		}
		
		LOGGER.debug("SensationFileSendServer end...");
	}
	
	private boolean fileReadingToBuffer(ByteBuffer buffer) throws IOException {
		return fileReadChannel.readingBlockSizeFromFile(buffer);
	}
	private void sendToServer(ByteBuffer byteBuffer) throws IOException {
		LOGGER.debug("file send to server.");
		channel.send(byteBuffer, serverInetSocketAddress);
		LOGGER.debug("file send complete");
	}

	private void setupDatagramChannel() throws IOException {
		channel = DatagramChannel.open();
	}
	
	public SensationFileSendServer(InetSocketAddress serverInetSocketAddress, FileReadChannel fileReadChannel) throws IOException {
		super();
		this.serverInetSocketAddress = serverInetSocketAddress;
		this.fileReadChannel = fileReadChannel;
		setupDatagramChannel();
	}
	
	public SensationFileSendServer(InetSocketAddress serverInetSocketAddress,
			DatagramChannel channel, FileReadChannel fileReadChannel) {
		super();
		this.serverInetSocketAddress = serverInetSocketAddress;
		this.channel = channel;
		this.fileReadChannel = fileReadChannel;
	}
	
}
